package gwtappcontainer.server;

import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;


public class Utils {            
       
    public static String getCloudSqlURL() throws RuntimeException {
           
        try {                  
            if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
                Class.forName("com.mysql.jdbc.GoogleDriver"); 
                
                String appId = ApiProxy.getCurrentEnvironment().getAppId();
                
                if (appId.equals("ishaportaldev")) 
                	return "jdbc:google:mysql://ishaportalproject:ishaportaldev/ishaportal?user=root";
                if (appId.equals("ishaportaluat"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportaluat/ishaportal?user=root";
                if (appId.equals("ishaportalstaging"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportalstaging/ishaportal?user=root";
                if (appId.equals("ishaportal"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportal/ishaportal?user=root";
                
                //wrong environment
                throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
                		"There is no cloud sql instance associated with app [" + appId + "]");
            }
           
            //dev environment                                              
            Class.forName("com.mysql.jdbc.Driver");
            if (null != System.getProperty("junittesting")) //junittesting
                return "jdbc:mysql://127.0.0.1:3306/ishaportaltest?user=root&password=root";
                        
            return "jdbc:mysql://127.0.0.1:3306/ishaportal?user=root&password=root";
            
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
       
    public static String getStackTraceAsString(Throwable e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
       
        return sw.toString();
    }                      
}

